/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.szitar.forum.server.dao;

import hu.szitar.forum.server.HibernateUtil;
import hu.szitar.forum.server.query.QueryParameter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author tircsil
 */
public abstract class BaseDAO<T> {
    protected static Session session;
    
    
    static {
        session = HibernateUtil.getSessionFactory().openSession();
    }
    
    public abstract List<T> findAll();
       
    public abstract T create(T object);
    
    public List<T> find(String query) {
        List<T> objects = new ArrayList<T>();
        try {
            
            session.beginTransaction();
            Query q = session.createQuery(query);
            objects = q.list();
            
            session.getTransaction().commit();
        } catch (HibernateException he) {
            he.printStackTrace();
        }
        return objects;
    }
    
    public List<T> find(String query, QueryParameter<?>... params) {
        List<T> objects = new ArrayList<T>();
        try {
            
            session.beginTransaction();
            Query q = session.createQuery(query);
            int idx = 0;
            for(QueryParameter<?> p : params){
                switch( p.getType()){
                    case TEXT:{
                        q.setString(idx, (String)p.getValue());
                        break;
                    }
                    case INTEGER:{
                        q.setInteger(idx, (Integer)p.getValue());
                        break;
                    }
                    case DATE:{
                        q.setDate(idx, (Date)p.getValue());
                        break;
                    }
                }
                idx++;
            }
            objects = q.list();
            
            session.getTransaction().commit();
        } catch (HibernateException he) {
            he.printStackTrace();
        }
        return objects;
    }
}
